package com.ruoyi.a2.service.impl;

import com.ruoyi.a2.domain.A2DynamicsInfo;
import com.ruoyi.a2.domain.A2Pdcc;
import com.ruoyi.a2.service.IA2DynamicsInfoService;
import com.ruoyi.a2.service.ITool2aBlankValueFillService;
import com.ruoyi.common.enums.CleanStatusEnum;
import com.ruoyi.common.enums.CommonOKNOEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;


@Slf4j
@Service
public class Tool2aBlankValueFillImpl implements ITool2aBlankValueFillService {

    @Autowired
    private IA2DynamicsInfoService a2DynamicsInfoService;

    /**
     * 空值填充
     * 实现思路如下：
     * （1）循环所有点位,当某条数据中经纬度为空时，并且与前1条的基准时间超过A2Pdcc.intervalTime（间隔时间）秒，则自动填充
     * （2）填充规则：取前1条与后1条数据的经纬度中间值
     *
     * @author :yanlixiong
     * @date :2025-02-17 09:28:54
     */
    @Override
    public List<A2DynamicsInfo> handle(List<A2DynamicsInfo> infoList, Integer intervalTime) {
        //秒换算成毫秒
        Integer intervalTimeNew = intervalTime * 1000;
        int size = infoList.size();
        for (int i = 0; i < size; i++) {
            A2DynamicsInfo info = infoList.get(i);
            int indexBefore = i > 0 ? i - 1 : i;
            A2DynamicsInfo infoBefore = infoList.get(indexBefore);
            int indexAfter = i < size-1 ? i + 1 : i;
            A2DynamicsInfo infoAfter = infoList.get(indexAfter);
            if (info.getLon() == null && info.getLat() == null) {
                long baseTimeDifference = Math.abs(info.getBaseTime().getTime() - infoBefore.getBaseTime().getTime());
                if (baseTimeDifference > intervalTimeNew) {
                    if(infoBefore.getLon()!=null && infoBefore.getLat()!=null && infoAfter.getLon()!=null && infoAfter.getLat()!=null ) {
                        double lonNew = (infoBefore.getLon() + infoAfter.getLon()) / 2;
                        double latNew = (infoBefore.getLat() + infoAfter.getLat()) / 2;
                        info.setLon(lonNew);
                        info.setLat(latNew);
                        String geom = "ST_SetSRID(ST_MakePoint(" + lonNew + ", " + latNew + "), 4326)";
                        info.setGeom(geom);
                        info.setCleanStatus(CleanStatusEnum.DATA_2.getCode());
                    }
                }
            }
            info.setHandleCleanStatus2(CommonOKNOEnum.OK.getCode());
            a2DynamicsInfoService.updateA2DynamicsInfo(info);
        }
        return infoList;
    }
}
